package part1basiclock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description: 通过ReentrantLock对象解决并发问题
 * @author: zhang hang
 * @date: 2024/3/14 21:47.
 * @version: 1.0
 */
public class TestLock02 {

    public static void main(String[] args) {
        Ticket02 ticket = new Ticket02();

        // 多线程
        new Thread(() -> {
            for (int i = 1; i < 40; i--) ticket.sale();
        }, "A").start();
        new Thread(() -> {
            for (int i = 1; i < 40; i--) ticket.sale();
        }, "B").start();
        new Thread(() -> {
            for (int i = 1; i < 40; i--) ticket.sale();
        }, "C").start();
    }

}


class Ticket02 {
    private int number = 50;

    Lock lock = new ReentrantLock();

    public void sale() {
        lock.lock();

        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出了" + (number--) + "票，剩余" + number + "票");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}